package com.zhu.salesmanagement.network;

import java.util.ArrayList;
import java.util.List;

import com.zhu.salesmanagement.SalesApplication;
import com.zhu.salesmanagement.StoreDownLoadActivity;
import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.models.CustomerItem;
import com.zhu.salesmanagement.provider.SalesSettings;
import com.zhu.salesmanagement.utils.Util;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

/**
 * 门店数据客户
 */
public class DownLoadCustomerData {

    private static final int SETUP_GETOFFICE = 1;
    private static final int SETUP_GETCITY = 2;
    private static final int SETUP_GETCUSTOMER = 3;

    private Context mContext = null;
    private Handler mHandler = null;
    private int mType = -1;
    private int mConnectStep = -1;
    private int retryCount = 0;
    private String mOfficeid = null;
    private String mProvinceid = null;
    private String mCityid = null;
    private ArrayList<CustomerItem> mCustomerList = null;
    private boolean isSyncing = false;

    /**
     * 构造函数
     * @param context 上下文
     * @param handler 请求结果返回
     */
    public DownLoadCustomerData(Context context, Handler handler){
        mContext = context;
        mHandler = handler;
    }

    /**
     * 开始同步营业所门店
     * @param officeid 营业所id
     */
    public void startSync(String officeid){
        mOfficeid = officeid;
        isSyncing = true;
        retryCount = 0;
        resetData();
        getSalesOfficeCustomerSC();
    }

    /**
     * 开始同步省份城市门店
     * @param provinceid 省id
     * @param cityid 城市id
     */
    public void startSync(String provinceid, String cityid){
        mProvinceid = provinceid;
        mCityid = cityid;
        isSyncing = true;
        retryCount = 0;
        resetData();
        getCityCustomerSC();
    }

    /**
     * 重试下载
     */
    private void retryConnect(){
        switch(mConnectStep){
            case SETUP_GETOFFICE:
                getSalesOfficeCustomerSC();
                break;
            case SETUP_GETCITY:
                getCityCustomerSC();
                break;
        }
    }

    /**
     * 获取营业所门店
     */
    private void getSalesOfficeCustomerSC(){
        mConnectStep = SETUP_GETOFFICE;
        PostMethod.requestEmployeeSalesOfficeCustomerSC(Util.mVerifyUserResult.id, Util.mVerifyUserResult.mUUID, mOfficeid, new XMLRPCMethodCallback() {
            public void callFinished(int status, Object result) {
                mCustomerList = ParseData.parseCustomer(result, mContext);
                if(mCustomerList != null){
                    retryCount = 0;
                    syncSuccessEnd();
                }else{
                    syncFail();
                }
            }
        }, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * 获取城市所有门店
     */
    private void getCityCustomerSC(){
        mConnectStep = SETUP_GETCITY;
        PostMethod.requestCityCustomerSC(Util.mVerifyUserResult.id, Util.mVerifyUserResult.mUUID, mCityid, new XMLRPCMethodCallback() {
            public void callFinished(int status, Object result) {
                mCustomerList = ParseData.parseCustomer(result, mContext);
                if(mCustomerList != null){
                    retryCount = 0;
                    syncSuccessEnd();
                }else{
                    syncFail();
                }
            }
        }, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * 同步成功
     */
    private void syncSuccessEnd(){
        if(Actions.DEBUG){
            Log.e("zhu","syncSuccessEnd");
        }
        saveSyncData();
        mConnectStep = -1;
        retryCount = 0;
        isSyncing = false;
        mHandler.sendEmptyMessage(StoreDownLoadActivity.REQUST_DWONLOADSUCCESSEND);
    }

    /**
     * 同步失败
     */
    private void syncFail(){
        if(Actions.DEBUG){
            Log.e("zhu","syncFail="+mConnectStep);
        }
        if(retryCount < 3){
            retryCount++;
            retryConnect();
        }else{
            retryCount = 0;
            mConnectStep = -1;
            isSyncing = false;
            mHandler.sendEmptyMessage(StoreDownLoadActivity.REQUST_DWONLOADFAIL);
        }
    }

    /**
     * 重置数据
     */
    private void resetData(){
        if(mCustomerList != null){
            mCustomerList.clear();
            mCustomerList = null;
        }
    }

    public boolean isSync(){
        return isSyncing;
    }

    /**
     * 保存同步数据
     */
    private void saveSyncData(){
        long startTime = System.currentTimeMillis();
//      String where = "";
//      int size = mCustomersList.size();
//      for(int i = 0; i < size; i++){
//          if(where.length() == 0){
//              where = SalesSettings.CustomerSColumns.CUSTOMER_ID +" = \"" + mCustomersList.get(i) + "\"";
//          }else{
//              where += " or " + SalesSettings.CustomerSColumns.CUSTOMER_ID +" = \"" + mCustomersList.get(i) + "\"";
//          }
//      }
//      if(where != null && where.length() > 0){
//          mContext.getContentResolver().delete(SalesSettings.CustomerSColumns.CONTENT_URI_NO_NOTIFICATION, where, null);
//      }
//      if(Actions.DEBUG){
//          Log.e("zhu","deletetime=" + (System.currentTimeMillis() - startTime));
//      }
        SyncUtils.saveCustomerList(mContext, mCustomerList);
        if(Actions.DEBUG){
            Log.e("zhu","savetime=" + (System.currentTimeMillis() - startTime));
        }
    }

    /**
     * 销毁数据
     */
    public void destroy(){
        resetData();
    }
}
